In [2]:
## Dealing with duplicate entries. Last value wins!
dict = {'Name': 'Alice', 'Age': 47, 'Name': 'Manni'}
print("dict['Name']: ", dict['Name'])
## Applying Function and Methods
breakfast = {'ham': 'roll', 'egg': 'scramble'}
lunch = {'burger': 'well', 'fries': 'yes', 'salad': 'yes'}
print("Length : %d" % len (lunch))
## seq -- list of values which would be used for dictionary keys preparation.
## value -- if provided then value would be set to this value
seq = ('name', 'height', 'sex')
dict = dict.fromkeys(seq)
print("New Dictionary : %s" % str(dict))
dict = dict.fromkeys(seq, 10,)
print ("New Dictionary : %s" % str(dict))
In [1]:
## Finding values in a dictionary
dict = {'Name': 'Paisely', 'Age': 27, 'Level': 'Sophomore'}
print(dict['Name'])
print(dict['Age'])
## Finding key that do not exist
## Using a try except clause
dict = {'Name': 'Haley', 'Age': 21, 'Level': 'Junior'}
try:
dict['Rainbow']
except KeyError:
print('pass')
## Updating a Dictionary
dict = {'Name': 'Paisely', 'Age': 27, 'Level': 'Sophomore'}
dict['Age'] = 19; # update existing dictionay
dict['College'] = "CUNY SPS"; # Add new entry
print("dict['Age']: ", dict['Age'])
print ("dict['College']: ", dict['College'])
## Delete Dictionary Elements.
dict = {'Name': 'Paisely', 'Age': 27, 'Level': 'Sophomore', 'College': 'CUNY SPS'}
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print("dict['Age']: ", dict['Age']) # will return an error since contents of dict was cleared
print("dict['School']: ", dict['School']) # will return an error since contents of dict was cleared
In [3]:
## Returns a value for the given key. If key is not available then returns default value None.
dict = {'Name': 'Cheray', 'Age': 27}
print("Value : %s" % dict.get('Age'))
print ("Value : %s" % dict.get('Education', "None"))
## Returns key value pairs as a list of tuples.
dict = {'rank': 'manager', 'Age': 47}
print ("Value : %s" % dict.items())
## Returns a list of Dictionary keys
dict = {'Room': 2, 'Tutor': 'Jennifer', 'Subject': 'Math'}
print ("Value : %s" % dict.keys())
## Returns a list of dictionary vlaues
dict = {'Room': 2, 'Tutor': 'Jennifer', 'Subject': 'Math'}
print ("Value : %s" % dict.values())
In [ ]: